// AI智能诊断功能 - 集成真实大模型API

// 添加症状到描述框
function addSymptomToDescription(symptom) {
    const textarea = document.getElementById('symptom-description');
    const currentText = textarea.value.trim();
    
    if (currentText === '') {
        textarea.value = symptom;
    } else {
        // 检查是否已经包含该症状
        if (!currentText.includes(symptom)) {
            textarea.value = currentText + ', ' + symptom;
        }
    }
    
    textarea.focus();
}

// 清空描述框
function clearAIDescription() {
    document.getElementById('symptom-description').value = '';
    hideDiagnosisResult();
}

// 提交AI诊断（集成真实大模型API）
async function submitAIDiagnosis() {
    const description = document.getElementById('symptom-description').value.trim();
    
    if (description === '') {
        showMessage('请输入症状描述', 'error');
        return;
    }
    
    // 显示加载状态
    showLoading();
    hideDiagnosisResult();
    
    try {
        // 使用真实的大模型API进行诊断
        const result = await callRealAIDiagnosisAPI(description);
        displayDiagnosisResult(result);
    } catch (error) {
        console.error('AI诊断失败:', error);
        showMessage('AI诊断服务暂时不可用，请稍后重试', 'error');
        
        // 降级到本地模拟诊断
        const fallbackResult = callLocalAIDiagnosisAPI(description);
        displayDiagnosisResult(fallbackResult);
    } finally {
        hideLoading();
    }
}

/**
 * 调用真实AI模型API
 */
async function callRealAIDiagnosisAPI(symptoms, model = 'local') {
    try {
        // 检查后端API服务是否可用
        const healthCheck = await fetch('http://localhost:3001/api/health', {
            method: 'GET',
            timeout: 5000
        }).catch(() => null);
        
        if (!healthCheck || !healthCheck.ok) {
            console.log('后端API服务不可用，使用本地模型');
            return await callLocalAIDiagnosisAPI(symptoms);
        }
        
        // 调用AI诊断API
        const response = await fetch('http://localhost:3001/api/ai-diagnosis', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                symptoms: symptoms,
                model: model
            }),
            timeout: 30000 // 30秒超时
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        
        if (data.success) {
            return {
                success: true,
                diagnosis: data.diagnosis,
                model: data.model,
                isRealAI: data.model !== 'local',
                modelUsed: data.model,
                fallback: data.fallback || false
            };
        } else {
            throw new Error(data.error || 'API调用失败');
        }
        
    } catch (error) {
        console.error('真实AI API调用失败:', error);
        // 降级到本地模拟模型
        return await callLocalAIDiagnosisAPI(symptoms);
    }
}

// 解析大模型响应并转换为标准格式
function parseAIModelResponse(aiResponse, modelName) {
    try {
        // 根据不同的模型响应格式进行解析
        const responseText = aiResponse.trim();
        
        // 检查响应是否有效
        if (!responseText || responseText.length < 10) {
            throw new Error('AI响应内容过短或无效');
        }
        
        // 提取可能疾病
        const conditions = extractConditionsFromResponse(responseText);
        
        // 提取建议
        const recommendations = extractRecommendationsFromResponse(responseText);
        
        // 评估严重程度
        const severity = assessSeverityFromResponse(responseText);
        
        // 生成紧急程度建议
        const urgency = generateUrgencyFromSeverity(severity);
        
        // 提取关键信息摘要
        const summary = extractSummaryFromResponse(responseText);
        
        return {
            success: true,
            severity: severity,
            urgency: urgency,
            conditions: conditions,
            recommendations: recommendations,
            generalAdvice: responseText,
            summary: summary,
            modelUsed: modelName,
            isRealAI: true,
            responseLength: responseText.length
        };
    } catch (error) {
        console.error('解析AI响应失败:', error);
        
        // 返回降级结果
        return {
            success: false,
            severity: 'unknown',
            urgency: '建议就医咨询',
            conditions: [{ name: '需要专业医生诊断', probability: '待评估' }],
            recommendations: [
                '建议前往医院进行专业检查',
                '详细描述症状给医生',
                '保持症状记录'
            ],
            generalAdvice: 'AI诊断服务暂时不可用，请咨询专业医生进行诊断',
            summary: '诊断服务暂时不可用',
            modelUsed: modelName,
            isRealAI: true,
            error: '解析失败',
            fallback: true
        };
    }
}

// 从响应中提取关键信息摘要
function extractSummaryFromResponse(response) {
    const lines = response.split('\n').filter(line => line.trim().length > 0);
    
    // 查找包含关键信息的行
    const importantLines = lines.filter(line => 
        line.includes('可能') || 
        line.includes('建议') || 
        line.includes('就医') ||
        line.includes('检查') ||
        line.includes('紧急')
    );
    
    if (importantLines.length > 0) {
        return importantLines.slice(0, 3).join(' | ');
    }
    
    // 如果没有找到关键信息，返回前几行
    return lines.slice(0, 2).join(' | ');
}

// 从响应中提取可能疾病
function extractConditionsFromResponse(response) {
    const conditions = [];
    
    // 使用正则表达式匹配疾病名称
    const conditionRegex = /([\u4e00-\u9fa5]+症|[\u4e00-\u9fa5]+炎|[\u4e00-\u9fa5]+病|[\u4e00-\u9fa5]+感染)/g;
    const matches = response.match(conditionRegex) || [];
    
    // 去重并添加概率
    const uniqueConditions = [...new Set(matches)];
    uniqueConditions.forEach((condition, index) => {
        // 根据出现顺序和关键词估算概率
        const probability = Math.max(80 - index * 10, 30) + '%';
        conditions.push({
            name: condition,
            probability: probability
        });
    });
    
    // 如果没有提取到疾病，添加默认项
    if (conditions.length === 0) {
        conditions.push({
            name: '需要进一步检查',
            probability: '待评估'
        });
    }
    
    return conditions;
}

// 从响应中提取建议
function extractRecommendationsFromResponse(response) {
    const recommendations = [];
    
    // 使用正则表达式匹配建议项
    const recommendationRegex = /[•\-\*]\s*([^\n]+)|\d+\.\s*([^\n]+)/g;
    let match;
    
    while ((match = recommendationRegex.exec(response)) !== null) {
        const recommendation = (match[1] || match[2]).trim();
        if (recommendation && recommendation.length > 5) {
            recommendations.push(recommendation);
        }
    }
    
    // 如果没有提取到建议，添加默认建议
    if (recommendations.length === 0) {
        recommendations.push(
            '建议前往医院进行专业检查',
            '详细描述症状给医生',
            '保持症状记录'
        );
    }
    
    return recommendations.slice(0, 5); // 最多返回5条建议
}

// 根据响应内容评估严重程度
function assessSeverityFromResponse(response) {
    const responseLower = response.toLowerCase();
    
    if (responseLower.includes('立即就医') || responseLower.includes('紧急') || responseLower.includes('危险')) {
        return 'high';
    } else if (responseLower.includes('尽快就医') || responseLower.includes('建议就医') || responseLower.includes('中度')) {
        return 'medium';
    } else {
        return 'low';
    }
}

// 根据严重程度生成紧急程度建议
function generateUrgencyFromSeverity(severity) {
    const urgencyMap = {
        'high': '建议立即就医',
        'medium': '建议尽快就医',
        'low': '建议观察'
    };
    return urgencyMap[severity] || '建议就医咨询';
}

// 本地模拟AI诊断API（降级方案）
function callLocalAIDiagnosisAPI(symptoms) {
    // 这里应该是真实的API调用，目前使用模拟数据
    const mockResults = {
        // 常见症状组合的模拟结果
        '头痛,发热': {
            severity: 'medium',
            urgency: '建议尽快就医',
            conditions: [
                { name: '上呼吸道感染', probability: '85%' },
                { name: '流感', probability: '70%' },
                { name: '普通感冒', probability: '60%' }
            ],
            recommendations: [
                '多休息，保持充足睡眠',
                '多喝水，保持水分补充',
                '可服用退烧药如布洛芬',
                '如症状持续3天以上请就医'
            ],
            generalAdvice: '注意观察体温变化，如出现呼吸困难请立即就医'
        },
        '咳嗽,胸闷': {
            severity: 'high',
            urgency: '建议立即就医',
            conditions: [
                { name: '支气管炎', probability: '75%' },
                { name: '肺炎', probability: '65%' },
                { name: '哮喘', probability: '50%' }
            ],
            recommendations: [
                '立即就医进行专业检查',
                '避免剧烈运动',
                '保持室内空气流通',
                '注意观察呼吸情况'
            ],
            generalAdvice: '胸闷症状需要高度重视，建议立即就医检查'
        },
        '乏力,头晕': {
            severity: 'low',
            urgency: '建议观察',
            conditions: [
                { name: '贫血', probability: '60%' },
                { name: '低血糖', probability: '55%' },
                { name: '睡眠不足', probability: '80%' }
            ],
            recommendations: [
                '保证充足睡眠',
                '均衡饮食，补充营养',
                '适当进行轻度运动',
                '避免突然站起'
            ],
            generalAdvice: '如症状持续或加重，建议进行血常规检查'
        }
    };
    
    // 根据症状关键词匹配最接近的结果
    let bestMatch = null;
    let maxScore = 0;
    
    for (const [key, result] of Object.entries(mockResults)) {
        const score = calculateMatchScore(symptoms, key);
        if (score > maxScore) {
            maxScore = score;
            bestMatch = result;
        }
    }
    
    // 如果没有匹配到预设结果，返回通用结果
    if (!bestMatch || maxScore < 0.3) {
        return {
            severity: 'medium',
            urgency: '建议就医咨询',
            conditions: [
                { name: '需要进一步检查', probability: '待评估' }
            ],
            recommendations: [
                '建议前往医院进行专业检查',
                '详细描述症状给医生',
                '保持症状记录'
            ],
            generalAdvice: 'AI无法准确判断，建议寻求专业医疗帮助'
        };
    }
    
    return bestMatch;
}

// 计算症状匹配度
function calculateMatchScore(inputSymptoms, targetSymptoms) {
    const inputWords = inputSymptoms.split(/[,，\s]+/).filter(word => word.length > 0);
    const targetWords = targetSymptoms.split(/[,，\s]+/).filter(word => word.length > 0);
    
    let matchCount = 0;
    for (const word of inputWords) {
        if (targetWords.some(target => target.includes(word) || word.includes(target))) {
            matchCount++;
        }
    }
    
    return matchCount / Math.max(inputWords.length, targetWords.length);
}

// 显示诊断结果
function displayDiagnosisResult(result) {
    const resultDiv = document.getElementById('diagnosis-result');
    
    // 更新严重程度标签
    const severityTag = document.getElementById('severity-tag');
    severityTag.textContent = getSeverityText(result.severity);
    severityTag.className = 'severity-tag severity-' + result.severity;
    
    const urgencyTag = document.getElementById('urgency-tag');
    urgencyTag.textContent = result.urgency;
    urgencyTag.className = 'severity-tag severity-' + result.severity;
    
    // 更新可能病症
    const conditionsDiv = document.getElementById('possible-conditions');
    conditionsDiv.innerHTML = result.conditions.map(condition => 
        `<div class="condition-item">
            <span class="condition-name">${condition.name}</span>
            <span class="condition-probability">${condition.probability}</span>
        </div>`
    ).join('');
    
    // 更新建议
    const recommendationsDiv = document.getElementById('recommendations');
    recommendationsDiv.innerHTML = result.recommendations.map(rec => 
        `<div class="recommendation-item">
            <i class="fas fa-check-circle"></i> ${rec}
        </div>`
    ).join('');
    
    // 更新通用建议
    document.getElementById('general-advice').textContent = result.generalAdvice;
    
    // 显示使用的AI模型信息（如果是真实大模型）
    const modelInfoDiv = document.getElementById('model-info');
    if (result.isRealAI && result.modelUsed) {
        modelInfoDiv.innerHTML = `
            <div class="model-info">
                <i class="fas fa-robot"></i>
                <span>AI诊断模型：${result.modelUsed}</span>
            </div>
        `;
        modelInfoDiv.style.display = 'block';
    } else {
        modelInfoDiv.style.display = 'none';
    }
    
    // 显示结果区域
    resultDiv.style.display = 'block';
    
    // 滚动到结果区域
    resultDiv.scrollIntoView({ behavior: 'smooth' });
}

// 获取严重程度文本
function getSeverityText(severity) {
    const texts = {
        'low': '轻度',
        'medium': '中度', 
        'high': '重度'
    };
    return texts[severity] || '待评估';
}

// 隐藏诊断结果
function hideDiagnosisResult() {
    document.getElementById('diagnosis-result').style.display = 'none';
}

// 显示加载状态
function showLoading() {
    document.getElementById('loading').style.display = 'block';
}

// 隐藏加载状态
function hideLoading() {
    document.getElementById('loading').style.display = 'none';
}

// 显示消息
function showMessage(message, type = 'info') {
    // 移除现有消息
    const existingMessage = document.querySelector('.message');
    if (existingMessage) {
        existingMessage.remove();
    }
    
    // 创建新消息
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.textContent = message;
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.remove();
        }
    }, 3000);
}

// 多页面导航功能
function navigateTo(page) {
    window.location.href = page;
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化底部导航
    const navButtons = document.querySelectorAll('.nav-btn');
    navButtons.forEach(button => {
        button.addEventListener('click', function() {
            navButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
        });
    });
    
    // 初始化症状输入框的自动调整高度
    const symptomTextarea = document.getElementById('symptom-description');
    if (symptomTextarea) {
        symptomTextarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
        });
    }
    
    console.log('症状自查小程序已初始化');
});

// 导出函数供HTML调用
window.addSymptomToDescription = addSymptomToDescription;
window.clearAIDescription = clearAIDescription;
window.submitAIDiagnosis = submitAIDiagnosis;